package jnpf.service.impl;

import jnpf.util.UserProvider;
import jnpf.entity.*;
import jnpf.mapper.TestMapper;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.test.*;
import java.math.BigDecimal;
import cn.hutool.core.util.ObjectUtil;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.util.GeneraterSwapUtil;
import jnpf.database.model.superQuery.SuperQueryJsonModel;
import jnpf.database.model.superQuery.ConditionJsonModel;
import jnpf.database.model.superQuery.SuperQueryConditionModel;
import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import java.util.regex.Pattern;
import jnpf.model.QueryModel;
import java.util.stream.Collectors;
import jnpf.base.model.ColumnDataModel;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.text.SimpleDateFormat;
import jnpf.util.*;
import java.util.*;
import jnpf.base.UserInfo;
import jnpf.permission.entity.UserEntity;
/**
 *
 * test
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-04-12
 */
@Service
public class TestServiceImpl extends ServiceImpl<TestMapper, TestEntity> implements TestService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Override
    public List<TestEntity> getList(TestPagination testPagination){
        return getTypeList(testPagination,testPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<TestEntity> getTypeList(TestPagination testPagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
        List<List<String>> intersectionList =new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? TestConstant.getAppColumnData() : TestConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total=0;
        int testNum =0;
        QueryWrapper<TestEntity> testQueryWrapper=new QueryWrapper<>();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp ="";
        if (ObjectUtil.isNotEmpty(testPagination.getSuperQueryJson())){
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList  = new ArrayList<>();
            String queryJson = testPagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<TestEntity> testSuperWrapper = new QueryWrapper<>();
            testSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(testSuperWrapper,TestEntity.class,queryJson,"0"));
            int testNum1 = testSuperWrapper.getExpression().getNormal().size();
            if (testNum1>0){
                List<String> testList =this.list(testSuperWrapper).stream().map(TestEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(testList);
                intersectionSuperList.add(testList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if(superOp.equalsIgnoreCase("and")){
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            }else{
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp ="";
        if (ObjectUtil.isNotEmpty(ruleJson)){
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList  = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<TestEntity> testSuperWrapper = new QueryWrapper<>();
            testSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(testSuperWrapper,TestEntity.class,ruleJson,"0"));
            int testNum1 = testSuperWrapper.getExpression().getNormal().size();
            if (testNum1>0){
                List<String> testList =this.list(testSuperWrapper).stream().map(TestEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(testList);
                intersectionRuleList.add(testList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if(ruleOp.equalsIgnoreCase("and")){
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            }else{
                allRuleIDlist = allRuleList;
            }
        }
    boolean pcPermission = false;
    boolean appPermission = false;
    if(isPc && pcPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object testObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(testQueryWrapper,TestEntity.class,testPagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(testObj)){
        return new ArrayList<>();
        } else {
        testQueryWrapper = (QueryWrapper<TestEntity>)testObj;
        if( testQueryWrapper.getExpression().getNormal().size()>0){
        testNum++;
        }
        }
    }
    }
    if(!isPc && appPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object testObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(testQueryWrapper,TestEntity.class,testPagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(testObj)){
        return new ArrayList<>();
        } else {
        testQueryWrapper = (QueryWrapper<TestEntity>)testObj;
        if( testQueryWrapper.getExpression().getNormal().size()>0){
        testNum++;
        }
        }


    }
    }
        if(isPc){
            if(ObjectUtil.isNotEmpty(testPagination.getNamelist())){
            testNum++;

                String value = testPagination.getNamelist() instanceof List ?
                    JsonUtil.getObjectToString(testPagination.getNamelist()) :
                    String.valueOf(testPagination.getNamelist());
                testQueryWrapper.lambda().like(TestEntity::getNamelist,value);

            }

            if(ObjectUtil.isNotEmpty(testPagination.getAddressList())){
            testNum++;

                String value = testPagination.getAddressList() instanceof List ?
                    JsonUtil.getObjectToString(testPagination.getAddressList()) :
                    String.valueOf(testPagination.getAddressList());
                testQueryWrapper.lambda().like(TestEntity::getAddressList,value);

            }

            if(ObjectUtil.isNotEmpty(testPagination.getNamelists())){
            testNum++;

                String value = testPagination.getNamelists() instanceof List ?
                    JsonUtil.getObjectToString(testPagination.getNamelists()) :
                    String.valueOf(testPagination.getNamelists());
                testQueryWrapper.lambda().like(TestEntity::getNamelists,value);

            }

            if(ObjectUtil.isNotEmpty(testPagination.getAgeList())){
            testNum++;

                String value = testPagination.getAgeList() instanceof List ?
                    JsonUtil.getObjectToString(testPagination.getAgeList()) :
                    String.valueOf(testPagination.getAgeList());
                testQueryWrapper.lambda().like(TestEntity::getAgeList,value);

            }

        }
        if(!isPc){
            if(ObjectUtil.isNotEmpty(testPagination.getAgeList())){
            testNum++;

                String value = testPagination.getAgeList() instanceof List ?
                    JsonUtil.getObjectToString(testPagination.getAgeList()) :
                    String.valueOf(testPagination.getAgeList());
                testQueryWrapper.lambda().like(TestEntity::getAgeList,value);

            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total>0){
            if (intersection.size()==0){
                intersection.add("jnpfNullList");
            }
            testQueryWrapper.lambda().in(TestEntity::getId, intersection);
        }
    //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)){
            if (allSuperIDlist.size()==0){
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            testQueryWrapper.lambda().and(t->t.in(TestEntity::getId, finalAllSuperIDlist));
        }
    //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)){
            if (allRuleIDlist.size()==0){
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            testQueryWrapper.lambda().and(t->t.in(TestEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if(StringUtil.isEmpty(testPagination.getSidx())){
            testQueryWrapper.lambda().orderByDesc(TestEntity::getNamelist);
        }else{
            try {
                String sidx = testPagination.getSidx();
                String[] strs= sidx.split("_name");
                TestEntity testEntity = new TestEntity();
                Field declaredField = testEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                testQueryWrapper="asc".equals(testPagination.getSort().toLowerCase())?testQueryWrapper.orderByAsc(value):testQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<TestEntity> page=new Page<>(testPagination.getCurrentPage(), testPagination.getPageSize());
                IPage<TestEntity> userIPage=this.page(page, testQueryWrapper);
                return testPagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<TestEntity> list = new ArrayList();
                return testPagination.setData(list, list.size());
            }
        }else{
            return this.list(testQueryWrapper);
        }
    }
    @Override
    public TestEntity getInfo(String id){
        QueryWrapper<TestEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(TestEntity::getId,id);
        return this.getOne(queryWrapper);
    }
    @Override
    public void create(TestEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String id, TestEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(TestEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(TestForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id="";
        String countRecover = "";
        if (isUp){
            id = form.getId();
        }
        //主表字段验证
//                if(StringUtil.isEmpty(form.getNamelists())){
//                    return "名称列表2不能为空";
//                }
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param testForm
    * @return
    */

    @Override
    @Transactional
    public void saveOrUpdate(TestForm testForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        testForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(TestConstant.getFormData(),testForm),TestForm.class);
        TestEntity entity = JsonUtil.getJsonToBean(testForm, TestEntity.class);

        if(isSave){
            String mainId =  RandomUtil.uuId() ;
        entity.setDjzj(generaterSwapUtil.getBillNumber("rukudanhao", false));
            entity.setId(mainId);
        }else{
        entity.setDjzj(generaterSwapUtil.getBillNumber("rukudanhao", false));
        }
        this.saveOrUpdate(entity);

    }
}
